﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.Windows.Ria;
using System.Windows.Data;
using System.Windows.Ria.ApplicationServices;
using System.Windows.Ria.Data;
using AlexApp;

namespace ExpenseReport
{
    /// <summary>
    /// Allows modification of an ExpenseReport and the individual ExpenseReportDetails via the
    /// ModifyExpenseDetailChildWindow.  All changes to details are batched and not saved until 
    /// the parent item is committed.
    /// </summary>
    public partial class UpdateExpenseReport : Page
    {
        public ExpenseReport currentExpenseReport = null;
        public ExpenseReportDetails currentExpenseReportDetail = null;

        private ModifyExpenseDetailChildWindow detailWindow = null;

        public UpdateExpenseReport()
        {
            InitializeComponent();

            expenseForm.ItemEditEnded += new EventHandler<DataFormItemEditEndedEventArgs>(expenseForm_ItemEditEnded);
        }

        /// <summary>
        /// Persists the changes to the server when data form has completed commiting an edit.
        /// </summary>
        private void expenseForm_ItemEditEnded(object sender, DataFormItemEditEndedEventArgs e)
        {
            if (e.EditAction == DataFormEditAction.Commit)
            {
                ods.SubmitChanges();
            }
            expenseForm.BeginEdit();
        }

        /// <summary>
        /// Retrieves the current expense report once the page is loaded.
        /// </summary>
        private void ods_Loaded(object sender, RoutedEventArgs e)
        {
            //if ExpenseReportId is 0 then this is a create path and there is no need to query
            //just create a new one.
            int expenseReportId = int.Parse(this.NavigationContext.QueryString["ExpenseReportId"]);
            if (expenseReportId == 0)
            {
                User currentUser = UserService.Current.User as User;
                ExpenseReport newExpenseReport = new ExpenseReport() 
                { 
                    RptStatus = ReportStatus.NotSubmitted,
                    Created=DateTime.Now.Date,
                    user = currentUser.Name
                };
                
                ((ExpenseData)ods.DomainContext).ExpenseReports.Add(newExpenseReport);
                expenseForm.CurrentItem = newExpenseReport;
                currentExpenseReport = newExpenseReport;
            }
            else //Set the load method parameter
            {
                ods.LoadParameters.Add(new Parameter() { ParameterName = "erId", Value = expenseReportId });
                ods.Load();
            }
        }

        /// <summary>
        /// Sets the current item for the expense report from.
        /// </summary>
        private void ods_LoadedData(object sender, LoadedDataEventArgs e)
        {
            DomainDataSource dataSource;
            if (sender is DomainDataSource)
            {
                dataSource = (DomainDataSource)sender;
                if (dataSource.DataView is IEnumerable)
                {
                    IEnumerable data = (IEnumerable)dataSource.Data;
                    IEnumerator dataEnumerator = data.GetEnumerator();

                    expenseForm.CurrentItem = dataEnumerator.MoveNext() ? dataEnumerator.Current : null;
                    currentExpenseReport = (ExpenseReport)expenseForm.CurrentItem;
                    expenseForm.BeginEdit();
                }
            }
        }

        /// <summary>
        /// Creates the detail window 
        /// </summary>
        private void createModifyExpenseDetailChildWindow()
        {
            if (detailWindow == null)
            {
                detailWindow = new ModifyExpenseDetailChildWindow();
            }
        }

        /// <summary>
        /// Creates ChildWindow to edit expense report detail and sets properties on ChildWindow
        /// to indicate parent DomainContext and ExpenseReprot
        /// </summary>
        private void btnEditClick(object sender, RoutedEventArgs e)
        {
            createModifyExpenseDetailChildWindow();

            //Set embedded window to point to selected ExpenseReportDetails.
            ExpenseReportDetails expenseReportDetail = currentExpenseReportDetail;
            detailWindow.DataContext = currentExpenseReport.ExpenseReportDetails;
            detailWindow.ParentDomainContext = (ExpenseData)ods.DomainContext;
            detailWindow.ParentExpenseReport = currentExpenseReport;
            detailWindow.DetailItem = expenseReportDetail;
            detailWindow.Show();
            
        }

        /// <summary>
        /// Creates a new expense reprot detail and sets the current item on the ChildWindow to point to it.
        /// </summary>
        private void btnAddClick(object sender, RoutedEventArgs e)
        {
            //Create new instance and add it to list.
            createModifyExpenseDetailChildWindow();
            ExpenseReportDetails newExpenseReportDetail = new ExpenseReportDetails()
                {
                    DateIncurred = DateTime.Now.Date
                };
            currentExpenseReportDetail = newExpenseReportDetail;
            detailWindow.DataContext = newExpenseReportDetail;
            detailWindow.ParentDomainContext = (ExpenseData)ods.DomainContext;
            detailWindow.ParentExpenseReport = currentExpenseReport;
            detailWindow.DetailItem = newExpenseReportDetail;
            detailWindow.Show();
        }

        /// <summary>
        /// Sets the current expense report detail when a datagrid selection changes.
        /// </summary>
        void editDetailsDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                currentExpenseReportDetail = (ExpenseReportDetails)e.AddedItems[0];
            }
        }

        /// <summary>
        /// Deletes the current expense report detail
        /// </summary>
        private void btnDeleteClick(object sender, RoutedEventArgs e)
        {
            currentExpenseReport.ExpenseReportDetails.Remove(currentExpenseReportDetail);
        }

    }
}
